from django.db import connection


def query_all_dict(sql, params=None,nopagesql=None):
    '''    查询所有结果返回字典类型数据
    :param sql:
    :param params:
    :return:
    '''

    with connection.cursor() as cursor:
        rowList = []
        num = 0
        if params:
            num = cursor.execute(sql, params=params)
        else:
            mum = cursor.execute(sql)
        col_names = [desc[0] for desc in cursor.description]
        row = cursor.fetchall()
        for list in row:
            tMap = dict(zip(col_names, list))
            rowList.append(tMap)
        if nopagesql:
            if params:
                num = cursor.execute(nopagesql, params=params)
            else:
                num = cursor.execute(nopagesql)
        return rowList, col_names,num

#
# def query_one_dict(sql, params=None):
#     """    查询一个结果返回字典类型数据
#     :param sql:
#     :param params:
#     :return:    """
#     with connection.cursor() as cursor:
#         if params:
#             cursor.execute(sql, params=params)
#         else:
#             cursor.execute(sql)
#         col_names = [desc[0] for desc in cursor.description]
#         row = cursor.fetchone()
#         tMap = dict(zip(col_names, row))
#         return tMap, col_names


def list_to_dict(data: list, userid: int):
    """返回字典
    :param list 字典列表
    :return: 返回字典
    """
    namelist = {}
    for i in data:
        if i["typed"] == 'int':
            a = {i["name"]: int(i["test"])}
        elif i["typed"] == "user":
            a = {i["name"]: userid}
        else:
            a = {i["name"]: i["test"]}
        namelist.update(a)
    return namelist


def dict_int_change(data: list, getdata: dict, userid: int):
    """把请求内的数字转换为数字
    """
    namelist = {}
    for i in data:
        if getdata.get(i["name"]):
            if i["typed"] == 'int':
                namelist.update({i["name"]: int(getdata[i['name']])})
            else:
                namelist.update({i["name"]: getdata[i['name']]})
        elif i["typed"] == 'user':
            namelist.update({i["name"]: userid})
    return namelist

